#include <iostream>

#include "Udp_server.hpp"
using namespace std;

void Useage(string proc)
{
    cout << "Useage" << proc << "serverport serverip" << endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    string sreverip;
};

void* recv_message(void * args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    char buffer[1024];
    while(true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        ssize_t n = recvfrom(td->sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
    }

}

void* sebder_message(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    string message;
    socklen_t len = sizeof(td->server);

    string welcome = td->sreverip;
    welcome += "comming...";
    sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(td->server), len);

    while(true)
    {
        cout << "please Enter@ ";
        getline(cin, message);

        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(td->server), len);
    }
}

// ./udpserver serverip serverport;
int main(int args, char* argv[])
{
    if(args != 3)
    {
        Useage(argv[0]);
        return 0;
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }

    td.sreverip = serverip;

    pthread_t recvr, sebder;
    pthread_create(&recvr, nullptr, recv_message, &td);
    pthread_create(&recvr, nullptr, sebder_message, &td);

    pthread_join(recvr, nullptr);
    pthread_join(sebder, nullptr);

    close(td.sockfd);
    return 0;
}